using System;
using System.IO;
using System.Net;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Xml;
using Hal;

namespace RESTAgent.Hal {
    
    public class HalFormatter : MediaTypeFormatter {

        public HalFormatter() {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.hal+xml"));
			SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/hal+xml"));
        }


        protected override bool CanReadType(Type type)
        {
            return type == typeof(HalDocument);
        }
        protected override bool CanWriteType(Type type)
        {
            return type == typeof(HalDocument);
        }

        protected override Task<object > OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
        {
            return new TaskFactory<object>().StartNew(() => HalDocument.Load(stream));
        }

        protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
        {
            return new TaskFactory().StartNew(() =>
            {
                var writer = XmlWriter.Create(stream);
                ((HalDocument)value).WriteAsXml(writer);
                writer.Flush();
            });
        }
        
    }
}
